//
//  RegisterCheckPhoneViewController.m
//  homeland
//
//  Created by caesar on 14-5-7.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "RegisterCheckPhoneViewController.h"
#import "UIView+Toast.h"
#import "LandingViewController.h"

@interface RegisterCheckPhoneViewController ()

@end

@implementation RegisterCheckPhoneViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"验证手机号";
    //设置手机号输入框不可编辑
    [self.phoneEditText setEnabled:NO];
    self.phoneEditText.text = self.phone;
    [UserInfoService getUserInfoService].delegate = self;

    self.navigationItem.rightBarButtonItem = rightNavBtnWithImgName(@"跳过", self, @selector(goBackIndexView));
    // Do any additional setup after loading the view from its nib.
}

- (void)goBackIndexView
{
    [[UserInfoService new]addUser:self.userName Password:self.password Phone:self.phone Address:self.address StreetId:self.choosedStreetId LiveHere:self.liveHere WorkHere:self.workHere Success:^(NSDictionary *data) {
        BOOL isSuccess = NO;
        isSuccess = ((NSNumber*)[data objectForKey:@"isSuccess"]).boolValue;
        if(isSuccess){
            //调用登录
            [[UserInfoService getUserInfoService] checkUserLoginWithName:self.userName andPassword:self.password];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"successLoginWithIndexViewController" object:nil];
        }else{
            NSString *message = [data objectForKey:@"message"];
            [self.view makeToast:message duration:3.0 position:@"center"];
        }
        
    } Failure:^(NSString *msg) {
        
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//注册成功回调函数
#pragma mark - User Info Service Methods
-(void)loadUserInfoFinished:(id)result
{
    //关闭加载框
    [self stopLoadingView];
    
    isStart=1;//成功登录
    //保存密码,自动登录，
    //保存用户信息
//    [[UserInfoService getUserInfoService] loginSuccessHandler:result];
 
    //----------
    //
    [DataStoreService saveToKeychain:AUTO_LOGIN_USER_NAME data:self.userName];
    [DataStoreService saveToKeychain:AUTO_LOGIN_USER_PASSWORD data:self.password];
    //跳到首页 LandingViewController
//    LandingViewController *landingViewController = [[LandingViewController alloc]initWithNibName:@"LandingViewController" bundle:nil];
//
//    [self.navigationController pushViewController:landingViewController animated:YES];
    
    //调用登录
    [[UserInfoService getUserInfoService] checkUserLoginWithName:self.userName andPassword:self.password];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"successLoginWithIndexViewController" object:nil];
    
}
////保存用户信息
//-(void)loginSuccessHandler:(id)json
//{
//    NSDictionary *infoCustomDic = [json objectForKey:@"infoCustom"];
//    NSDictionary *userDic = [json objectForKey:@"user"];
//    self.userCustomInfo = getObjectFromDic([UserCustomInfo class], infoCustomDic);
//    self.userInfo = getObjectFromDic([UserInfo class], userDic);
//    [UserInfoService getUserInfoService].lastLoginPassword=self.userInfo.password;
//    self.userInfo.isStart=@"1";//判断是否已经登录-/**0代表未登录，1代表已登录。2，代表已登录注消**/
//    isStart=1;//判断是否已经登录-/**0代表未登录，1代表已登录。2，代表已登录注消**/
//    [DataStoreService saveToKeychain:AUTO_LOGIN_USER_PASSWORD data:self.userInfo.password];
//    self.currentLoginUserName = _userInfo.userName;
//    if (_userCustomInfo&&!isBlankString(_userCustomInfo.userStreetId)) {
//        [StreetInfoService getService].selectedStreetId = _userCustomInfo.userStreetId;
//    }
//注册失败回调函数
-(void)loadUserInfoFaild:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [self stopLoadingView];
}
//注册方法
-(void)addUser{

    [[UserInfoService new]addUser:self.userName Password:self.password Phone:self.phone Address:self.address StreetId:self.choosedStreetId LiveHere:self.liveHere WorkHere:self.workHere Success:^(NSDictionary *data) {
        BOOL isSuccess = NO;
        isSuccess = ((NSNumber*)[data objectForKey:@"isSuccess"]).boolValue;
        
        if(isSuccess){
        //调用登录
         [[UserInfoService getUserInfoService] checkUserLoginWithName:self.userName andPassword:self.password];
        }else{
            NSString *message = [data objectForKey:@"message"];
            [self.view makeToast:message duration:3.0 position:@"center"];
        }
        
    } Failure:^(NSString *msg) {
        
    }];
}
//提交
- (IBAction)postBtnAction:(id)sender {
    
    
    NSString * checkNum = self.checkNumEditText.text;
    if (!checkNum || checkNum.length == 0) {
        [self.view makeToast:@"验证码不能为空" duration:3.0 position:@"center"];
        return;
    }
    if (!self.phone || self.phone.length == 0) {
        [self.view makeToast:@"手机号码不能为空！" duration:3.0 position:@"center"];
        return;
    }
    
    if(![self isMobileNO:self.phone]){
        [self.view makeToast:@"请填写正确的手机号码！" duration:3.0 position:@"center"];
    }
     [self startLoadingViewWithText:@"正在注册..."];
    //请求后台，参数：手机号，和验证码 ：提交成功 调用注册
    [[UserInfoService new] valiNum:self.phone checkNumber:checkNum  Success:^(NSDictionary *data) {
        BOOL isSuccess = NO;
        isSuccess = ((NSNumber*)[data objectForKey:@"isSuccess"]).boolValue;
        NSString *message = [data objectForKey:@"message"];
        if (isSuccess) {
            [self.view makeToast:message duration:3.0 position:@"center"];
            //请求注册
            [self addUser];
        }else{
            
            [self.view makeToast:message duration:3.0 position:@"center"];
        }
    } Failure:^(NSString *msg) {
        [self.view makeToast:@"请求失败" duration:3.0 position:@"center"];
    }];
    
}
//请求验证码并倒计时
- (IBAction)timeBtnAction:(id)sender {
    if( countDownTimer != nil){
         NSLog(@"  is not equery nil");
    }else{
        NSLog(@"  is  nil");
        //启动倒计时
        countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
        //请求后台
 
        [[UserInfoService new] getPhoneCheckNumber:self.phone Success:^(NSDictionary *data) {
            BOOL isSuccess = NO;
            isSuccess = ((NSNumber*)[data objectForKey:@"isSuccess"]).boolValue;
            NSString *message = [data objectForKey:@"message"];
            if (isSuccess) {
                [self.view makeToast:message duration:3.0 position:@"center"];
            }else{
                [self.timeBtn setTitle:@"获取" forState:UIControlStateNormal];
                [countDownTimer invalidate];
                countDownTimer = nil;
                secondsCountDown = 60;//60秒倒计时
                [self.view makeToast:message duration:3.0 position:@"center"];
            }
        } Failure:^(NSString *msg) {
             [self.view makeToast:@"请求失败" duration:3.0 position:@"center"];
        }];
        
    }
}
NSInteger secondsCountDown = 60;//60秒倒计时
NSTimer *countDownTimer = nil;
-(void)timeFireMethod{
    secondsCountDown--;
    NSString *timeStr = @"";
    timeStr = [NSString stringWithFormat: @"%d",secondsCountDown];

    timeStr = [timeStr stringByAppendingString:@"秒"];
  
    [self.timeBtn setTitle:timeStr forState:UIControlStateNormal];
 
    if(secondsCountDown==0){
        [self.timeBtn setTitle:@"获取" forState:UIControlStateNormal];
        [countDownTimer invalidate];
        countDownTimer = nil;
        secondsCountDown = 60;//60秒倒计时
    }
    
    if( 0 > secondsCountDown){
        [self.timeBtn setTitle:@"获取" forState:UIControlStateNormal];
        [countDownTimer invalidate];
        countDownTimer = nil;
        secondsCountDown = 60;//60秒倒计时
    }
    
}

/**
 * 是否为电话号码 11位数  前三位数以
 * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
 * 联通：130、131、132、152、155、156、185、186
 * 电信：133、153、180、189、（1349卫通）开头
 * return true 是正确的手机号  false 是不正确的手机号
 * **/
-(BOOL)isMobileNO:(NSString *)mobiles {
    NSString *mobilesRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobilesRegex];
    return [emailTest evaluateWithObject:mobiles];
}
@end
